﻿using Application.Common.Interfaces;
using FluentValidation;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Users.Commands.Update;

public class ResetPasswordCommandValidator : AbstractValidator<ResetPasswordCommand>
{
    private readonly IApplicationDbContext _context;
    public ResetPasswordCommandValidator(IApplicationDbContext context)
    {
        _context = context;

        RuleFor(v => v.UserId)
             .MustAsync(BeValidUserAsync!).WithMessage($"数据不存在！");
    }

    /// <summary>
    /// 校验用户
    /// </summary>
    /// <param name="command">修改参数</param>
    /// <param name="userId">用户唯一标识</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回布尔值</returns>
    private async Task<bool> BeValidUserAsync(ResetPasswordCommand command, long userId, CancellationToken cancellationToken)
    {
        var user = await _context.Users.SingleOrDefaultAsync(x => x.Id == userId && x.ConcurrencyStamp == command.ConcurrencyStamp);
        if (user == null) return false;

        return true;
    }
}